package com.john.bms.config.shiro;

import com.john.bms.config.redis.RedisStringService;
import com.john.bms.model.system.user.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author:张家小帅哥
 * @Date:2020/9/23 14:52
 * @Version:1.0
 * @Description:登录限制次数
 */
@Slf4j
public class RetryLimitHashedCredentialsMatcher extends SimpleCredentialsMatcher {

    @Autowired
    RedisStringService redisUtils;

    public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {
//        passwordRetryCache = cacheManager.getCache("passwordRetryCache");
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {


        //获取用户名
        String username = (String) token.getPrincipal();
        PrincipalCollection principals = info.getPrincipals();
        SysUser primaryPrincipal = (SysUser) principals.getPrimaryPrincipal();
        //获取用户登录次数
        String errorNum = (String) redisUtils.get("lock=id" + primaryPrincipal.getId() + "name=" + username);
        Integer count = 0;
        if (errorNum != null && !"".equals(errorNum)) {
            count = Integer.valueOf(errorNum);
            if (count >= 5) {
                //抛出用户锁定异常
                throw new LockedAccountException();
            }
        }

        //判断用户账号和密码是否正确
        boolean matches = super.doCredentialsMatch(token, info);
        if (matches) {
            //如果正确,从缓存中将用户登录计数 清除
            redisUtils.remove("lock=id" + primaryPrincipal.getId() + "name=" + username);
        } else {
            redisUtils.set("lock=id" + primaryPrincipal.getId() + "name=" + username, String.valueOf(++count), 60 * 10L);
        }

        return matches;

    }

}
